<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\store\shop;

use app\common\model\store\shop\Manage as ManageModel;
use app\store\service\store\User as UserService;
use think\facade\Db;

/**
 * 商家门店店员模型
 * Class Manage
 * @package app\store\model\store\shop
 */
class Manage extends ManageModel
{
    // 表单验证场景: 新增
    const FORM_SCENE_ADD = 'add';

    // 表单验证场景: 编辑
    const FORM_SCENE_EDIT = 'edit';

    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAll(array $param = []): \think\Collection
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->with(['user.avatar', 'shop'])
            ->where($filter)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc', $this->getPk()])
            ->select();
    }

    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->with(['user.avatar', 'shop'])
            ->where($filter)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc', $this->getPk()])
            ->paginate(15);
    }

    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询参数
        $params = $this->setQueryDefaultValue($param, [
            'shop_id' => 0,  // 门店id
            'search'  => '', // 搜索关键词: 姓名/手机号
            'status'  => '', // 门店状态(0禁用 1启用)
            'type'    => 1,  // 主管类别
        ]);
        // 检索查询条件
        $filter = [];

        if ($params['shop_id'] > 0) {
            $manage   = Db::name('jia_manage_build')->where('shop_id', $params['shop_id'])->field('manage_id')->select()->toArray();
            $ids      = array_column($manage, 'manage_id');
            $filter[] = ['clerk_id', 'in', $ids];
        }
        // 门店状态
        is_numeric($params['status']) && $filter[] = ['status', '=', (int) $params['status']];
        $filter[]                                  = ['type', '=', (int) $params['type']];
        // 搜索关键词
        ! empty($params['search']) && $filter[] = ['real_name|mobile', 'like', "%{$params['search']}%"];
        return $filter;
    }

    /**
     * 新增记录
     * @param array $data
     * @return bool
     */
    public function add(array $data): bool
    {
        // 表单验证
        if (! $this->validateForm($data, self::FORM_SCENE_ADD)) {
            return false;
        }

        $data['store_id'] = self::$storeId;

        $this->save($data);

        //ManageBuildModel::increased($this['clerk_id'], $data['shop_ids']);
        return true;
    }
/**
 * 更换
 * @param array $data
 * @return bool|false
 */
    public function change($orderId, array $data): bool
    {
        Db::name('order')->where('order_id', $orderId)->update(['manage_id' => $data['manageId']]);
        $userInfo = UserService::getLoginInfo();
        //记录
        $dd['store_id']      = self::$storeId;
        $dd['create_time']   = time();
        $dd['old_manage_id'] = $data['oldId'];
        $dd['manage_id']     = $data['manageId'];
        $dd['order_id']      = $orderId;
        $dd['admin_id']      = $userInfo['user']['store_user_id'];
        Db::name('store_shop_manage_log')->insert($dd);

        return true;
    }
    /**
     * 编辑记录
     * @param array $data
     * @return bool|false
     */
    public function edit(array $data): bool
    {
        $data['type'] = $this['type'];
        // 表单验证
        if (! $this->validateForm($data, self::FORM_SCENE_EDIT, $this)) {
            return false;
        }

        //$data['shop_ids'] = json_encode($data['shop_ids']);

        //ManageBuildModel::increased($this['clerk_id'], $data['shop_ids']);

        return $this->save($data) !== false;
    }

    /**
     * 软删除
     * @return bool|false
     */
    public function setDelete(): bool
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 表单验证
     * @param $data
     * @param string $scene
     * @param mixed $detail
     * @return bool
     */
    private function validateForm($data, string $scene, $detail = null): bool
    {
        $data['shop_id'] = 10001;
        if ($scene === self::FORM_SCENE_ADD) {
            if (empty($data['user_id'])) {
                $this->error = '请选择指定的用户';
                return false;
            }
            if (self::isExistForShop($data['user_id'], $data['shop_id'], $data['type'])) {
                $this->error = '该用户已经是主管，无需重复添加';
                return false;
            }
        }
        if ($scene === self::FORM_SCENE_EDIT) {
            if ($data['shop_id'] != $detail['shop_id'] && self::isExistForShop($detail['user_id'], $data['shop_id'], $detail['type'])) {
                $this->error = '该用户已经是主管，无需重复添加';
                return false;
            }
        }
        return true;
    }

    /**
     * 验证门店是否已存在该店员
     * @param int $userId
     * @param int $shopId
     * @return bool
     */
    private function isExistForShop(int $userId, int $shopId, int $type): bool
    {
        $model = new static;
        return (bool) $model->where('user_id', '=', $userId)
        //->where('shop_id', '=', $shopId)
            ->where('type', '=', $type)
            ->where('is_delete', '=', 0)
            ->value($model->getPk());
    }
}
